//
//  WWHomeViewController.swift
//  SinWEiBo
//
//  Created by 胡良志 on 2018/3/11.
//  Copyright © 2018年 HuLiangZhi. All rights reserved.
//

import UIKit
import SVProgressHUD
import MJRefresh

let defaultCellID = "defaultCellID"
let retWeetedCellID = "retWeetedCellID"
let homeDB = "homeDB"
var count : Int = 0
class WWHomeViewController: WWBaseViewController {

    lazy var homeViewModel : WWHomeViewModel = WWHomeViewModel() //viewModel

    @objc private func bk(){
        self.navigationController?.pushViewController(WWDemo_1_Controller(), animated: true)
    }

    

    override func viewDidLoad() {
        super.viewDidLoad()
        SVProgressHUD.show()
        if !userLogin {
            SVProgressHUD.dismiss()
            //设置访客视图的信息 --> 获取访客视图
            visitor.updateInfo(title: "关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            return
        }
        //扫一扫
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(bk))
        
        setupTableView()
            loadData()
        
    
        
}
    //加载数据
    @objc private func loadData (){
        //加载数据
        homeViewModel.loadData(isPullup: activity.isAnimating) { (isSuccess : Bool,count : Int) in
            if !isSuccess{ SVProgressHUD.dismiss()
                return
            }
            SVProgressHUD.dismiss()
            //获取到数据停止转动
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                // 上拉刷新不提示label
                if !self.activity.isAnimating{
                     self.startAnimation(count: count) //////
                }
                self.tableView.mj_header.endRefreshing()
                self.activity.stopAnimating()
                self.tableView.refreshControl?.endRefreshing()
                self.tableView.reloadData()
            }
        }
    }
    
    private func setupTableView (){
        let defaultNib = UINib(nibName: "WWStatusCell", bundle:nil )
        let retWeetedNib = UINib(nibName: "WWretWeetedCell", bundle: nil)
        self.tableView.register(defaultNib, forCellReuseIdentifier: defaultCellID)
        self.tableView.register(retWeetedNib, forCellReuseIdentifier: retWeetedCellID)
        self.tableView.estimatedRowHeight = 400
        self.tableView.rowHeight = UITableViewAutomaticDimension //自动计算行高
        self.tableView.separatorStyle = .none //隐藏cell分割线
        self.tableView.tableFooterView = activity
        self.tableView.delegate = self
        self.tableView.dataSource = self
        //上拉刷新
//        refreshControl = UIRefreshControl()
//        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        self.tipLabel.frame = CGRect(x: 0, y: 64 - 35, width: ScreenWidth, height: 35)
//        self.navigationController?.view.addSubview(tipLabel)
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: (self.navigationController?.navigationBar)!)
        
        //下拉刷新
        let header = MJRefreshNormalHeader()
        header.setRefreshingTarget(self, refreshingAction: #selector(loadData))
        self.tableView.mj_header = header
    }
    
    //提示显示多少条数据
    private func startAnimation(count : Int){
        //如果正在做动画直接return
        if tipLabel.isHidden == false {
            return
        }
        let tip = count == 0 ? "没有新微博" : "有\(count)条微博"
        self.tipLabel.text = tip
        self.tipLabel.isHidden = false
        //初始值的Y
        let Y = self.tipLabel.frame.origin.y
        //修改tipLabel的Y值
        UIView.animate(withDuration: 1, animations: {
            self.tipLabel.frame.origin.y = 64 
        }) { (_) in
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = Y
            }, completion: { (_) in
                self.tipLabel.isHidden = true
            })
        }
    }
    
    //上拉菊花控件
    private lazy var activity : UIActivityIndicatorView = {
        let ac = UIActivityIndicatorView(activityIndicatorStyle: .gray)
//        ac.startAnimating()
        return ac
    }()
    //提示的label
    private lazy var tipLabel : UILabel = {
       let label = UILabel(title: "", fountSize: 14, textColor:UIColor.white)
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        label.alpha = 0.9
        label.isHidden = true
        return label
    }()
    
}

//MARK: 数据源
extension WWHomeViewController {
//    override func numberOfSections(in tableView: UITableView) -> Int {
//        return 1
//    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.dataArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.homeViewModel.dataArray[indexPath.row]
        let cellID = getCellID(viewModel: model)
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! WWStatusCell

        cell.selectionStyle = .none //选中样式.默认

        cell.viewModel = model
        return cell
    }
    
    //cell即将显示的时候调用
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if activity.isAnimating == false && indexPath.row == homeViewModel.dataArray.count - 2 {
            activity.startAnimating()
            //加载数据
            self.loadData()
//            activity.stopAnimating()
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        count = count + 1
//        print(count)
        self.tableView.estimatedRowHeight = 400
        
        return  UITableViewAutomaticDimension //自动计算行高
    }

//    //先调用获取行高的协议方法
//    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        //获取cell
//        let viewmodel = self.homeViewModel.dataArray[indexPath.row]
//        //let cellId = getCellId(viewmodel: viewmodel)
//        //从缓存池中获取一个cell
//        //由于tableView要显示先调用获取行高的方法  -> 在行高的方法内部会获取缓存的cell  -> dequeueReusableCell: indexPath内部会调用 heightForRowAt: --> 形成递归调用
//        //获取cell的时候就不能够使用 dequeueReusableCell: indexPath
//        //使用NSBundle的方式加载cell文件']\
//        let name = nibName(viewmodel: viewmodel)
//        let cell = UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil).last as! WWStatusCell
//        //let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HMStatusCellpri
//        //绑定数据
//        cell.viewModel = viewmodel
//        //cell是自动布局, 设置了数据自动布局并没有立即生效
//        cell.layoutIfNeeded()
////        print(cell.toolBar.frame.maxY)
////        return cell.toolBar.frame.maxY
//    }
    
    //根据数据源选择不同的cell
    private func getCellID (viewModel:WWStatusViewModel) -> String{
        return viewModel.status?.retweeted_status == nil ? defaultCellID : retWeetedCellID
    }
    
    private func nibName(viewmodel: WWStatusViewModel) -> String {
        return (viewmodel.status?.retweeted_status == nil) ? "WWStatusCell" : "WWretWeetedCell"
    }
    
    
}

















